package com.ha7419x.fallback;

import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class DeptProviderFallback implements ZuulFallbackProvider {
    @Override
    public String getRoute() {
        return "demo-provider-dept";  // 失败的 服务路由
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.BAD_REQUEST;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.BAD_REQUEST.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.BAD_REQUEST.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(
                        "{\"deptNo\":\"7777\",\"deptName\":\"【ERROR】demo-zuul-gateway-9501\",\"loc\":\"【ERROR】demo-zuul-gateway-9501\"}"
                                .getBytes());//服务调用失败的返回内容
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type" , "text/html; charset=UTF-8");
                return headers;
            }
        };
    }
}
